package com.starsea.book.ui.newpage.activity

import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.BarUtils
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.databinding.ActivitySearchResultBinding
import com.starsea.book.ui.newpage.adapter.SearchBookResultAdapter
import com.starsea.book.ui.newpage.viewmodel.HomeViewModel
import com.starsea.book.utils.startActivity
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding

/**
 * @author Lee
 * @createTime 2024-08-18 18 GMT+8
 * @desc :
 */
class SearchResultActivity : VMBaseActivity<ActivitySearchResultBinding, HomeViewModel>() {

    lateinit var mAdapter: SearchBookResultAdapter

    var keyWord = ""
    var pageNo = 1

    override val viewModel: HomeViewModel by viewModels<HomeViewModel>()
    override val binding: ActivitySearchResultBinding by viewBinding(ActivitySearchResultBinding::inflate)

    override
    fun onActivityCreated(savedInstanceState: Bundle?) {

        BarUtils.addMarginTopEqualStatusBarHeight(binding.llTitle)

        keyWord = intent.getStringExtra("keyWord") ?: ""
        mAdapter = SearchBookResultAdapter(this)
        binding.rvContent.layoutManager = LinearLayoutManager(this)
        binding.rvContent.adapter = mAdapter

        mAdapter.keyword = keyWord

        binding.rtvSearch.setOnClickListener {
            val keyWordChild = binding.etContent.text.toString()
            if (TextUtils.isEmpty(keyWordChild)) {
                toastOnUi("请输入搜索关键字")
                return@setOnClickListener
            }
            keyWord = keyWordChild
            mAdapter.keyword = keyWordChild
            pageNo = 1
//            viewModel.getKeySearh(keyWord, pageNo = pageNo)
        }

        binding.srlRefresh.setOnRefreshListener {
            pageNo = 1
//            viewModel.getKeySearh(keyWord, pageNo)
        }

        binding.srlRefresh.setOnLoadMoreListener {
            pageNo++
//            viewModel.getKeySearh(keyWord, pageNo)
        }

//        viewModel.getKeySearh(keyWord, pageNo = pageNo)
        viewModel.keySearchBook.observe(this) {
            if (it.status == 200
            ) {
                if (pageNo == 1) {
                    mAdapter.submitList(it.data)
                    binding.srlRefresh.finishRefresh()
                } else {
                    binding.srlRefresh.finishLoadMore()
                    mAdapter.addAll(it.data!!)
                    if (it.data!!.size < 10) {
                        binding.srlRefresh.finishLoadMoreWithNoMoreData()
                    }
                }
            }
        }

    }


}